package com.zhongjian.technologycal.mall.activity.personal.activity;


import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.bean.JsonBean;
import com.zhongjian.technologycal.mall.bean.LoginBean;
import com.zhongjian.technologycal.mall.bean.ProvinceBean;
import com.zhongjian.technologycal.mall.http.BaseSubscriber;
import com.zhongjian.technologycal.mall.http.ExceptionHandle;
import com.zhongjian.technologycal.mall.http.MyApiService;
import com.zhongjian.technologycal.mall.http.RetrofitClient;
import com.zhongjian.technologycal.mall.utils.GetJsonDataUtil;
import com.zhongjian.technologycal.mall.utils.KeyBoardUtils;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.StatusBarUtil;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;
import com.zhongjian.technologycal.mall.utils.ValidatorUtils;
import com.zhongjian.technologycal.mall.view.EaseSwitchButton;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by wei on 2017/12/13.
 * 添加新地址页面的实现
 */

public class AddNewsAddressActivity extends BaseActivity {
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    @BindView(R.id.choice_tv_area)
    TextView choice_tv_area;
    @BindView(R.id.et_details_adr)
    EditText et_details_adr;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_username)
    EditText et_username;
    @BindView(R.id.setting_switch_button)
    EaseSwitchButton setting_switch_button;


    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ProvinceBean> options1Items1 = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private  int pid;
    private  int cid ;
    private  int aid ;
    private boolean isLoaded = false;
    private int status = 1;


    @Override
    protected void beforeInit() {
        super.beforeInit();
        super.beforeInit();
//        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.border_color));
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
    }
    @Override
    public void initPresenter() {

    }
    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_main_title.setText("添加新地址");
//        initJsonData();
        initJsonData1();
        setting_switch_button.openSwitch();

        setting_switch_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (setting_switch_button.isSwitchOpen()) {
                    setting_switch_button.closeSwitch();
                    status= 0;
                } else {
                    setting_switch_button.openSwitch();
                    status=1;
                }
            }
        });


    }

    @OnClick(R.id.iv_back_page)
    public void onClickFinish() {
        finish();
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_add_new_address;

    }

    /**
     * 选择省市区
     */
    @OnClick(R.id.choice_tv_area)
    public void onClickChoiceArea() {
        KeyBoardUtils.closeKeybord(et_details_adr,getBaseContext());
        KeyBoardUtils.closeKeybord(et_phone,getBaseContext());
        KeyBoardUtils.closeKeybord(et_username,getBaseContext());
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items1.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
                choice_tv_area.setText(tx);
                pid = options1Items1.get(options1).getId();
                cid = options1Items1.get(options1).getCitys().get(options2).getId();
                aid = options1Items1.get(options1).getCitys().get(options2).getRegions().get(options3).getId();
            }
        })
                .setTitleText("城市选择")
                .setTitleColor(getResources().getColor(R.color.color_items_college))
                .setDividerColor(getResources().getColor(R.color.color_items_college))
                .setTextColorCenter(getResources().getColor(R.color.blue)) //设置选中项文字颜色
                .setContentTextSize(15)
                .build();
//        pvOptions.setPicker(options1Items1);//一级选择器
//        pvOptions.setPicker(options1Items, options2Items);//二级选择器
        pvOptions.setPicker(options1Items1, options2Items, options3Items);//三级选择器
        pvOptions.setSelectOptions(13,0,4);
        pvOptions.show();

    }
    //解析数据
    private void initJsonData() {
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
//                Log.i("----",detail.get(i).getName());

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }


    //解析数据
    private void initJsonData1() {
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */

        String JsonData = new GetJsonDataUtil().getJson(this, "province_citys.json");//获取assets目录下的json文件数据

        ArrayList<ProvinceBean> jsonBean = parseData1(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items1 = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCitys().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCitys().get(c).getCityname();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCitys().get(c).getRegions() == null
                        || jsonBean.get(i).getCitys().get(c).getRegions().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int d = 0; d < jsonBean.get(i).getCitys().get(c).getRegions().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCitys().get(c).getRegions().get(d).getRegionname();
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

    }

    public ArrayList<ProvinceBean> parseData1(String result) {//Gson 解析
        ArrayList<ProvinceBean> detail = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < jsonArray.length(); i++) {
                ProvinceBean entity = gson.fromJson(jsonArray.optJSONObject(i).toString(),ProvinceBean.class);
                detail.add(entity);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    @OnClick(R.id.tv_save_commit)
    public void onClickSaveCoommit(){
        if(TextUtils.isEmpty(et_username.getText().toString().trim())){
            ToastUitl.showShort("收货人不能为空～");
            return;

        }else if(TextUtils.isEmpty(et_phone.getText().toString().trim())){
            ToastUitl.showShort("手机号不能为空～");
            return;
        }else if(!ValidatorUtils.isMobile(et_phone.getText().toString().trim())){
            ToastUitl.showShort("手机号不合法～");
            return;
        }else if(TextUtils.isEmpty(et_details_adr.getText().toString().trim())){
            ToastUitl.showShort("详细地址不能为空～");
            return;
        }else if(!NetWorkUtils.isNetConnected(getBaseContext())){
            ToastUitl.showShort("网络没有连接，请稍后重试～");
            return;
        }else{
            MyApiService service = RetrofitClient.getInstance(getBaseContext()).create(MyApiService.class);
            Map<String, Object> maps = new HashMap<>();
            maps.put("token",UserUtils.getUserToken());
            maps.put("CountryId", 1);
            maps.put("ProvinceId", pid);
            maps.put("CityId",cid);
            maps.put("RegionId",aid);

            maps.put("DetailAddress",et_details_adr.getText().toString().trim());
            maps.put("Name",et_username.getText().toString().trim());
            maps.put("Phone",et_phone.getText().toString().trim());
            maps.put("IsDefault",status);
            RequestBody body = RequestBody.create(
                    okhttp3.MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(maps));
            RetrofitClient.getInstance(getBaseContext()).createBaseApi().execute(
                    service.jsonAddAddress(body), new BaseSubscriber<LoginBean>(getBaseContext()) {
                        @Override
                        public void onStart() {
                            super.onStart();
                            LoadingDialog.showDialogForLoading(AddNewsAddressActivity.this,"提交中...",false);
                        }

                        @Override
                        public void onError(ExceptionHandle.ResponeThrowable e) {
                            Log.e("Lyk", e.getMessage());

                        }

                        @Override
                        public void onNext(LoginBean loginBean) {
                            ToastUitl.showShort(loginBean.getError_message());
                            finish();
                        }

                        @Override
                        public void onCompleted() {
                            super.onCompleted();
                            LoadingDialog.cancelDialogForLoading();
                        }
                    });


        }


    }

}
